<template>
    <div>
        <div :id="editorName" :style="{ width: width + 'px' }" v-if="name.length"></div>
        <!-- <span v-show="show">{{ name.length }}</span> -->
        <div :id="editorName" :style="{ width: width + 'px' }" v-else></div>
    </div>
</template>

<script lang="ts" setup>

import { CommonHelper } from '@/core/CommonHelper';
import { onMounted, watch, onUnmounted, ref, defineProps, withDefaults, defineEmits } from 'vue'


/**
 * 组件参数
 */
interface IProps {

    /**
     * 绑定值
     */
    modelValue: string;

    /**
     * UE富文本框的名称 不存则默认设置
     */
    name?: string;

    /**是否只读 */
    readonly?: boolean;

    /**宽度 */
    width?: number;

    /**高度 */
    height?: number;
}


const props = withDefaults(defineProps<IProps>(), {
    name: CommonHelper.getGUIDAsNot(),
    width: 800,
    height: 800,
    readonly: false
})

const emits = defineEmits(["update:modelValue"]);

const show = ref(false);
let editor: any;
let editorName = ref(props.name);
onMounted(() => {
    editor = UE.getEditor(editorName.value);
    editor.ready(function () {
        editor.setContent(props.modelValue);
        editor.setHeight(props.height);
    });

    editor.addListener("selectionchange", function () {
        emits("update:modelValue", editor.getContent())
    });
})

//卸载组件清理编辑器对象
onUnmounted(() => {
    if (editor) {
        editor.destroy();
        editor = null;
    }
})

//监听值改变
watch(() => props.modelValue, (newValue) => {
    if (editor) {
        editor.setContent(newValue);
    }
})
</script>